﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using WikeSoft.Core.Exception;
using WikeSoft.Core.Extension;
using WikeSoft.Data.Models;
using WikeSoft.Enterprise.Interfaces.Sys;
using WikeSoft.Enterprise.Models.Sys;

namespace WikeSoft.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly IPageService _pageService;
        //private readonly ISystemSettingService _systemSettingService;
        private readonly IUserService _userService;
      
   
        private readonly IKeyValueService _keyValueService;
        public HomeController(IPageService pageService, IUserService userService, IKeyValueService keyValueService)
        {
            _pageService = pageService;
           // _systemSettingService = systemSettingService;
            _userService = userService;
           
            
            _keyValueService = keyValueService;
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var systemSetting = _keyValueService.GetValue("SystemTitle");
            ViewBag.SystemTitle = systemSetting;
            return View();
        }

        /// <summary>
        /// Welcome
        /// </summary>
        /// <returns></returns>
        [PasswordExpiration]
        public ActionResult Welcome()
        {
           


            
            return View();
        }





        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult Login()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index");
            }
            var systemSetting = _keyValueService.GetValue("SystemTitle"); ;
            ViewBag.SystemTitle = systemSetting;

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, AllowAnonymous]
        public ActionResult Login(LoginModel model)
        {
            if (!ModelState.IsValid)
                return  View(model);


            var loginResult = _userService.Login(model);
            if (loginResult.LoginSuccess)
            {

                var authenticationManager = HttpContext.GetOwinContext().Authentication;
                var claims = new List<Claim>
                {
                    new Claim("LoginUserId", loginResult.UserId.ToString()),
                    new Claim("TrueName", loginResult.TrueName),
                    new Claim(ClaimTypes.Name, loginResult.UserName),
                    new Claim("UserRole",loginResult.Roles.Select(c=>c.Id).Join(";"))
                };
                loginResult.Roles.ForEach(c =>
                {
                    claims.Add(new Claim("RolesGroup", c.Id.ToString()));
                });

                var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                var pro = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.Now.AddHours(8)
                };
                authenticationManager.SignIn(pro, identity);

                if (HttpContext.Request.Url != null)
                {
                   
                }

                if (model.ReturnUrl.IsBlank())
                    return RedirectToAction("Index");
                return Redirect(model.ReturnUrl);
            }
            ModelState.AddModelError("LoginError", loginResult.LoginError);
            var systemSetting = _keyValueService.GetValue("SystemTitle");
            ViewBag.SystemTitle = systemSetting;
            return View(model);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        [Log("退出登录")]
        public ActionResult Logout()
        {
            HttpContext.GetOwinContext().Authentication.SignOut();
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 导航菜单
        /// </summary>
        /// <returns></returns>
        [ChildActionOnly]
        [HttpGet]
        [UnifyMvcSiteHandleError(MvcResultType = MvcResultType.PartialHtml)]
        public PartialViewResult _Nav()
        {
            var userId = User.Identity.GetLoginUserId();
            var pages = _pageService.GetPagesByUserId(userId);
            return PartialView("_Nav", pages);
        }

        /// <summary>
        /// Test
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [UnifyMvcSiteHandleError(MvcResultType = MvcResultType.Modal)]
        public ActionResult IndexPartial()
        {
            throw new TipInfoException("xxx");
            //return PartialView("Index");
        }

    }
}